# wordpress.py
# Original Author: Amar Zumkhawala (amarzumkhawala@gmail.com)
# Project URL - http://code.google.com/p/feedflare-categories
# Distributed under Apache License 2.0
#
# $Revision: 8 $, $Date: 2008-12-28 01:09:36 -0500 (Sun, 28 Dec 2008) $
# $Author: amarzumkhawala $

import logging
from google.appengine.api import urlfetch
from blogservice import AbstractBlogService, BlogEntry
from urlparse import urlparse

"""Wordpress implementation of AbstractBlogService"""
class WordpressService(AbstractBlogService):
  def __init__(self, id):
    self._blogEntry = self.parse(id)
  
  def blogEntry(self):
    return self._blogEntry

  """Fetch the complete blog xml for the given blog"""
  def fetchBlogXml(self, blogEntry):
      url = urlparse(blogEntry.atomId())
      postfeedurl = "http://" + url.hostname + "/feed"
      logging.info("wordpress urlfetch: " + postfeedurl);

      try :
        result = urlfetch.fetch(postfeedurl)
      except Exception:
        # raise new exception with more details
        logging.exception("exception during url fetch")
        raise Exception("urlfetch for feed " + postfeedurl + " resulted in exception")
 
      if result.status_code != 200:
        raise Exception("Http error in url fetch: " + str(result.status_code))

      atomEntryXml = result.content
      return atomEntryXml

  """Build url to webpage that searches the blog for posts labeled with the 
  first found category. 
  """ 
  def getBlogSearchByCategoryUrl(self, atomEntry):
    categories = atomEntry.categories()
    blogSearchByCategoryUrl = ""
    if len(categories) > 0:
      blogSearchByCategoryUrl = atomEntry.blogUrl() + "topics/" + atomEntry.categories()[0]
    return blogSearchByCategoryUrl

  def parse(self,id):
    if len(id) == 0:
      raise Exception("No id parameter given")
    
    # use the given id as the atom id
    blogEntry = BlogEntry()
    blogEntry.setAtomId(id)

    return blogEntry
